package main

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"net/http"
	"net/url"
	"time"
)

// 订单
type Order struct {
	Id       int
	Name     string
	Mids     string // 菜Id，组合
	Rices    int    // 米饭
	Timeline int
}

type Orders []Order

type OrderController struct {
	Controller
}

func (o *OrderController) Init(rw http.ResponseWriter, form url.Values) {
	o.Rw = rw
	o.Form = form
	o.Tpl = "order.tpl"
	log.Printf("c.form is :%T, %v\n", o.Form, o.Form)
	log.Println("加载order...")
}

func (o *OrderController) Get() {
	vdata := make(map[string]interface{}, 2)
	vdata["title"] = "orders"
	vdata["ods"] = getOrderToday()
	o.Display(vdata)
}

func (o *OrderController) Post() {

	od := make(map[string]string)
	od["name"] = o.Form.Get("name")
	od["mids"] = o.Form.Get("mids")
	od["rices"] = o.Form.Get("rices")
	od["timeline"] = timeline()

	db, err := sql.Open("sqlite3", DbName)
	checkErr(err)
	defer db.Close()

	stmt, err := db.Prepare("insert into orders (name,mids,rices,timeline) values (?,?,?,?)")
	checkErr(err)
	defer stmt.Close()
	res, err := stmt.Exec(od["name"], od["mids"], od["rices"], od["timeline"])
	checkErr(err)
	if id, _ := res.LastInsertId(); id > 0 {
		log.Println("追加id:", id)
		o.Get()
	}

}

func getOrderToday() (ods Orders) {
	db, err := sql.Open("sqlite3", DbName)
	checkErr(err)
	defer db.Close()

	stmt, err := db.Prepare("select id,name,mids,rices,timeline from orders where timeline>? ")
	checkErr(err)
	defer stmt.Close()

	todaystart := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Local).Unix()
	log.Println("today start on : ", todaystart)
	rows, err := stmt.Query(todaystart)
	defer rows.Close()

	for rows.Next() {
		o := Order{}
		err = rows.Scan(&o.Id, &o.Name, &o.Mids, &o.Rices, &o.Timeline)
		checkErr(err)
		ods = append(ods, o)
	}

	return
}
